package com.petAdoption.manager.controller;


import com.petAdoption.manager.util.OssUtil;
import com.petAdoption.manager.util.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@CrossOrigin("*")
public class OssUploadController {

    @Resource
    private OssUtil ossUtil;

    @PostMapping("/upload")
    public ResponseResult<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀  ****.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString()+ extension;

            String filePath = ossUtil.upload(file.getBytes(), objectName);
            System.out.println("====================");
            System.out.println(filePath);
            return ResponseResult.ok(filePath);

        } catch (IOException e) {
            log.error("文件上传失败",e);
        }

        return ResponseResult.error("文件上传失败");
    }
}

